package org.jsping.loginservlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.jsping.entity.User;
import org.jsping.service.ILoginUserService;
import org.jsping.service.impl.LoginUserServiceImpl;
import org.jsping.util.AuthUtil;

import com.alibaba.fastjson.JSONObject;

/**
 * 处理用户微信登录的请求
 */
@WebServlet("/WXcallBack.do")
public class WXCallBackServlet extends HttpServlet{
	private static final long serialVersionUID = 1L;
	//用户登录/注册业务处理
	private ILoginUserService loginUser = new LoginUserServiceImpl();
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		//获取到腾讯发送过来的code
		String code = req.getParameter("code");
		//使用code获取openid和userInfo
		String url = "https://api.weixin.qq.com/sns/oauth2/access_token?"
				+ "appid="+AuthUtil.WXAPPID
				+ "&secret="+AuthUtil.WXAPPSECRET
				+ "&code="+code
				+ "&grant_type=authorization_code";
		JSONObject json = AuthUtil.doGetJson(url);
		String openid = json.getString("openid");
		String token = json.getString("access_token");
		//使用openid和userInfo获取用户详细信息
		String userInfo = "https://api.weixin.qq.com/sns/userinfo?"
				+ "access_token="+token
				+ "&openid="+openid
				+ "&lang=zh_CN";
		//获取到用户的数据
		JSONObject uinfo = AuthUtil.doGetJson(userInfo);
		
		//增加微信用户
		//微信性别返回的是男/女，所以需要判断,男==1，女==2,未知==0
		User u = new User(uinfo.getString("nickname"),openid,uinfo.getIntValue("gender"),uinfo.getString("figureurl_qq_1"));
		//返回布尔值...?有什么用？
		loginUser.addOpenidUser(u);
		User newsU = loginUser.obtain(u.getOpenid());
		//昵称
		Cookie uname = new Cookie("uname", uinfo.getString("nickname"));
		//头像
		Cookie uimg = new Cookie("img", uinfo.getString("headimgurl"));
		//性别
		Cookie usex = new Cookie("sex", uinfo.getString("sex"));
		Cookie uid = new Cookie("uid",newsU.getUid()+"");
		resp.addCookie(uname);
		resp.addCookie(uimg);
		resp.addCookie(usex);
		resp.addCookie(uid);
		HttpSession session = req.getSession();
		session.setAttribute("user", "wx");
		resp.sendRedirect("index.jsp");
	}
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		this.doGet(req, resp);
	}
}
